package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.SetmealVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

/**
 * ClassName: OrderServiceImpl
 * Package:
 * Description
 * Pc 端-订单接口
 *
 * @Author xw
 * @Create 2023/11/25 18:13
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    /*
     * 地址
     * */
    @Autowired
    private AddressBookMapper addressBookMapper;

    /*
     * 购物车
     * */
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /*
     * 订单
     * */
    @Autowired
    private OrderMapper orderMapper;

    /*
     * 订单详情表
     * */
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    // 菜品--持久层
    @Autowired
    private DishMapper dishMapper;

    /*
     * 套餐
     * */
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     */
    @Override
    public OrderSubmitVO PostSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        // 用户id
        Long userId = BaseContext.getCurrentId();


        // 判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        // 查看购物车是否有数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.showShoppingCart(shoppingCart);
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        // 查询地址表，获得（用户名、手机号、地址、收货人）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //构造订单数据
        Orders orders = new Orders();
        // 拷贝
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 订单号
        orders.setNumber(UUID.randomUUID().toString());
        // 订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 用户id
        orders.setUserId(userId);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付状态
        orders.setPayStatus(Orders.UN_PAID);

        //-------------------- 地址表查询数据添加 --------------------
        // 手机号
        orders.setPhone(addressBook.getPhone());
        // 地址
        orders.setAddress(addressBook.getDetail());
        // 收货人
        orders.setConsignee(addressBook.getConsignee());


        //向订单表插入1条数据
        orderMapper.insert(orders);


        // 订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        // 向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.cleanShoppingCart(userId);

        // 返回数据
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付（阉割版修改状态）
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public String payment(OrdersPaymentDTO ordersPaymentDTO) {


        LocalDateTime now = LocalDateTime.now();

        Orders orders = new Orders();
        orders.setCheckoutTime(now); // 结账时间
        orders.setPayMethod(ordersPaymentDTO.getPayMethod()); // 结账方法
        orders.setPayStatus(Orders.PAID);  // 已支付
        orders.setNumber(ordersPaymentDTO.getOrderNumber()); // 订单号
        orders.setStatus(Orders.TO_BE_CONFIRMED); // 待接单

        orderMapper.update(orders);

        // 根据订单号查询，订单
        Long id = orderMapper.OrderNumber(ordersPaymentDTO.getOrderNumber());



        return id.toString();
    }

    /**
     * 历史订单查询
     */
    @Override
    public PageResult historyOrders(int page, int pageSize, Integer status) {

        try {
            PageHelper.startPage(page, pageSize);
            // 用户 id
            Long currentId = BaseContext.getCurrentId();

            // 分页条件查询
            Page<Orders> pageQuery = orderMapper.pageQuery(currentId, status);
            // 返回集合
            List<OrderVO> list = new ArrayList<>();
            // 查询出订单明细，并封装入OrderVO进行响应
            if (pageQuery != null && pageQuery.getTotal() > 0) {
                for (Orders orders : pageQuery) {
                    Long orderId = orders.getId();// 订单id
                    // 查询订单明细
                    List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(orders, orderVO);
                    orderVO.setOrderDetailList(orderDetails);

                    list.add(orderVO);
                }
            }
            return new PageResult(pageQuery.getTotal(), list);


        } catch (Exception e) {
            log.info("--->：{}", e.getMessage());
        }


        return null;
    }


    /**
     * 查询订单详情
     */
    @Override
    public Orders orderDetailID(Integer id) {

        Orders o = orderMapper.orderDetailID(id);

        // 查询菜品详情
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(o.getId());

        o.setOrderDetailList(byOrderId);


        return o;
    }


    /**
     * 取消订单
     */
    @Override
    public void cancelId(Long id) {

        Orders orders = new Orders();
        orders.setId(id);
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(6);
        orderMapper.cancelId(orders);
    }

    /**
     * 再来一单
     */
    @Override
    public void repetitionId(Long id) {

        // 订单详情
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(id);


        // 添加到购物车中
        ShoppingCart shoppingCart = new ShoppingCart();

        // 用户id
        Long userid = BaseContext.getCurrentId();
        shoppingCart.setUserId(userid);


        // 插入购物车
        for (OrderDetail orderDetail : byOrderId) {
            log.info("orderDetail->：{}", orderDetail);
            // 拷贝
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            // 插入
            shoppingCartMapper.insert(shoppingCart);
        }


    }


    /*-----------------------------管理端 订单------------------------------------*/

    /**
     * 订单搜索
     */
    @Override
    public PageResult PutCancel(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 设置分页数据
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());


        // 管理端 订单
        Page<OrderVO> pageQuery = orderMapper.PutCancels(ordersPageQueryDTO);
        log.info("管理端 订单：{}", pageQuery);

        // 封装返回数据
        List<OrderVO> list = new ArrayList<>();


        for (Orders orders : pageQuery) {

            Long orderId = orders.getId();// 订单id

            // 查询订单明细
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();

            StringBuffer stringBuffer = new StringBuffer();

            // 订单菜品信息
            orderDetails.forEach(
                    i -> {
                        // 菜品
                        Dish dish = dishMapper.getById(i.getDishId() + "");

                        // 套餐
                        SetmealVO byId = setmealMapper.getById(i.getSetmealId());

                        String name = (dish != null) ? dish.getName() : byId.getName();
                        stringBuffer.append(name).append("  ");
                    }
            );

            stringBuffer.append(";");

            // 拷贝
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            orderVO.setOrderDishes(stringBuffer.toString());

            list.add(orderVO);

        }


        return new PageResult(pageQuery.getTotal(), list);
    }


    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO Statistics() {

        List<Orders> orders = orderMapper.Statistics();

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        //待接单数量
        int toBeConfirmed = 0;

        //待派送数量
        int confirmed = 0;

        //派送中数量
        int deliveryInProgress = 0;

        for (Orders i : orders) {
            if (i.getStatus() == 2) {
                toBeConfirmed++;
            }

            if (i.getStatus() == 3) {
                confirmed++;
            }

            if (i.getStatus() == 4) {
                deliveryInProgress++;
            }

        }

        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);

        orderStatisticsVO.setConfirmed(confirmed);

        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单、拒单、取消订单、派送订单、完成订单
     */
    @Override
    public void update(Orders orders) {
        log.info("数据：{}", orders);
        orderMapper.cancelId(orders);
    }

    /**
     * 催单
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.orderDetailID(Integer.valueOf(id.toString()));
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
